package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private INoticeService noticeService;

    @RequestMapping("/empLogin")
    @ResponseBody
    public JsonResult empLogin(String username, String password, HttpSession session) {
        Employee employee = employeeService.login(username, password);
        //  session.setAttribute("USER_IN_SESSION",employee);
        UserContext.setContextUser(employee);
        Long eid = UserContext.getContextUser().getId();
        UserContext.setUnreadnumInSession(noticeService.getUnreadNum(eid)); //更改session中未读消息数量
        UserContext.setUnreadInSession(noticeService.getUnread(eid));
        if (!employee.isAdmin()) {
            List<String> expressions = permissionService.selectByEmpId(employee.getId());
            //session.setAttribute("EXPRESSIONS_IN_SESSION",expressions);
            UserContext.setExpression(expressions);
        }
        return new JsonResult();
    }

    @RequestMapping("/empLogout")
    public String logout(HttpSession session) {
        session.invalidate(); //销毁当前session
        return "redirect:/login.html";
    }

    @RequestMapping("/nopermission")
    public String nopermission() {
        return "common/nopermission";
    }
}
